#include "stofac.h"

int main (int ac, char **av)
{
  /* First populate the problem */
  int status;
  int i,j,k;

  /* Creat the data */
  int ni = atoi(av[1]);   //|I|
  int ns = atoi(av[2]);   //|W|
  //  double delta = atof(av[3]);
  double t0, t1;
  double tbigm, tcopy;
  double objval, objvalcopy;
  int *bigmrowind;
  int *bigmcolind;
  int *bigmchgind;
  double eps = 0.3;
  int loopind = 0;
  BIGMINFO minfo;
  /* Initialize CPLEX environment */
  CPXENVptr env = CPXopenCPLEX (&status);

  /* Creat one instance of the problem*/
  CPXLPptr lp   = CPXcreateprob (env, &status, "fac");

  /* Read paramters from .prm file */
  status = CPXreadcopyparam(env, "param/stofac.prm");

  /* Direct output to a logfile */
  FILE* logfile = NULL;
  logfile = CPXfopen("stofac.log", "w");
  status = CPXsetlogfile(env, logfile);

  /* Populate the model */
  status = DZpopulatemod(env, lp, ni, ns, eps);

  /* Clone the problem */
  CPXLPptr copy  = CPXcloneprob  (env, lp, &status);

  /* Access big-m coeffficients and print */
  status = DZgetbigmind(env, lp, &bigmrowind, &bigmcolind, &bigmchgind);
  //  status = DZprintbigmval(env, lp, bigmrowind, bigmcolind);

  minfo.ni = ni; //= ni;
  minfo.ns = ns; //= ns;
  minfo.bigmrowind = bigmrowind;
  minfo.bigmcolind = bigmcolind;
  minfo.bigmchgind = bigmchgind;
  minfo.loopind = &loopind;
  minfo.nbigm = ni*ns;

  /* Set up solve callback functions*/
  status = CPXsetsolvecallbackfunc (env, DZcallbacksetbigm, &minfo);
  if (status) goto TERMINATE;
  
  status = DZsetbigmval(env, lp, bigmrowind, bigmcolind);

  /* Solve the original model */
  status = CPXgettime(env, &t0);
  status = CPXmipopt(env, copy);
  status = CPXgettime(env, &t1);
  tcopy = t1 - t0;
  status  = CPXgetmipobjval (env, copy,   &objvalcopy);

  /* Solve the model */
  status = CPXgettime(env, &t0);
  status = CPXmipopt(env, lp);
  status = CPXgettime(env, &t1);
  tbigm = t1 - t0;
  status  = CPXgetmipobjval (env, lp,   &objval);

  printf("Objective by bigm  solver:    %f    Elapsed time: %f\n", objval, tbigm);
  printf("Objective by cplex solver:    %f    Elapsed time: %f\n", objvalcopy, tcopy);

  //  status = CPXwriteprob(env, lp, "stofac.lp", NULL);


 /* Change the bigM values and resolve */
  /*
  status = CPXreadcopyparam(env, "param/stofac.prm");
  status = DZchgbigmval(env, lp, bigmrowind, bigmcolind);
  //  status = DZprintbigmval(env, lp, bigmrowind, bigmcolind);
  status = CPXmipopt(env, lp);
  */

  /* Output the model */
  //  status = CPXwriteprob(env, lp, "stofac1.lp", NULL);
  //  if(status) goto TERMINATE;

 TERMINATE:
  CPXfclose(logfile);
  CPXfreeprob (env, &lp);
  CPXfreeprob (env, &copy);
  CPXcloseCPLEX (&env);

  free(bigmrowind);
  free(bigmcolind);

  return 0;
}
